//
//  TWFXDealWeatherDataOfDownLoad.m
//  TWFXWeather
//
//  Created by Lion User on 13-10-17.
//  Copyright (c) 2013年 Lion User. All rights reserved.
//

#import "TWFXDealWeatherDataOfDownLoad.h"


int indexOfDownLoad = -1;

@implementation TWFXDealWeatherDataOfDownLoad


-(id)init
{
    if (self = [super init]) {
        
        self.singleClass = [TWFXSingleClass sharedTWFXSingleClass];
        self.con = [[[TWFXNSConnection alloc] init] autorelease];
        self.con.delegateOfCon = self;
        
        self.weatherInfo = [[[TWFXStruct_AllWeatherInfo alloc] init] autorelease];
    }
    
    return self;
}

-(void)initCityInfoOfDownLoad:(TWFXStruct_AllWeatherInfo*) weatherInfo indexOfCurrentCity:(int) index
{

    //引用真TM危险,还是重新new一个好
    self.weatherInfo = [[[TWFXStruct_AllWeatherInfo alloc] init] autorelease];
    self.weatherInfo.countID = weatherInfo.countID;
    self.weatherInfo.countName = weatherInfo.countName;
    self.weatherInfo.countPY = weatherInfo.countPY;
    self.weatherInfo.cityName = weatherInfo.cityName;
    self.weatherInfo.cityPY = weatherInfo.cityPY;
    self.weatherInfo.proName = weatherInfo.proName;
    
    indexOfDownLoad = index;

}


//发起下载
-(void)beginDownLoadCityWeatherData
{
    if (![TWFXNSConnection isNetworkReachable]) {

        [self.delegateOfDealData DownLoadDataHavedDealed:nil];
        return;
    }
    

    
    @try {
        
        [MobClick event:@"downLoad"];
              
        self.con.flag_requestTime = 0;
        
     //   NSLog(@"实时天气发起下载请求");
        NSURL *urlOfRealTimeWeather = [self.singleClass URL_realTImeWeather:self.weatherInfo.countID];
        [self.con DownLoadByURL:urlOfRealTimeWeather];
        
     //   NSLog(@"未来天气发起下载请求");
        NSURL *urlOfFutureWeather = [self.singleClass URL_futureWeather:self.weatherInfo.countID];
        [self.con DownLoadByURL:urlOfFutureWeather];
        
      //  NSLog(@"aqi发起下载请求");
        NSURL *urlOfAqi = [self.singleClass URL_AQI:self.weatherInfo.cityName];
        [self.con DownLoadByURL:urlOfAqi];
        
    }
    @catch (NSException *exception) {
        
        NSLog(@"%@",exception.description);
    }
    @finally {
        //  NSLog(@"yichangbuhuo");
    }
    
}


//下载完成调用的回调函数
//根据URL来确定是下载什么数据的,然后调用相关的处理方法
-(void) DownloadIsSucceed:(id)result strOfURL:(NSString *)str_URL
{

    NSString *str_result = [[[NSString alloc] initWithData: result encoding:NSUTF8StringEncoding] autorelease];
    
    NSRange range = [str_result rangeOfString:@"error"];
//    if (range.length > 0 ) {
//        
//        NSLog(@"下载正常完成,但由于URL参数或没有查询到相关信息等原因,返回的数据不是正常情况下想要的");
//        
//        //  NSError *error = nserror
//        [self downloadIsFail:nil URL:str_URL];
//        return;
//    }
    
    NSData *resultData = [str_result dataUsingEncoding:NSUTF8StringEncoding];
    
    //将json字符串解析成dictionary格式的数据
    NSError *error = nil;
    id resultDic = [NSJSONSerialization JSONObjectWithData:(NSData*)resultData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&error];
    
    //如果能正确解析成Dictionary数据
    if (error == nil)
    {
        NSLog(@"%@", str_URL);
        
        if ([str_URL hasPrefix:@"http://m.weather.com.cn"])
        {
            if (range.length > 0) {
                
                self.weatherInfo.futureWeatherInfo = nil;
               
            }
            else
            {
               // NSLog(@"%@", resultDic);
                [self dealDownloadFutureWeather:resultDic];
            }
  
        }
        
        else if ([str_URL hasPrefix:@"http://www.weather.com.cn/data/sk/"])
        {
            if (range.length > 0) {
                
                self.weatherInfo.realTimeWeatherInfo = nil;
                
            }
            else
            {
                [self dealDownRealTimeWeather:resultDic];
            }
            

        }
        
        else if ([str_URL hasPrefix:@"http://www.pm25.in/api/querys"])
        {
            if (self.weatherInfo.realTimeWeatherInfo.temp == NULL) {
                
                NSLog(@"bug  something wrong");
            }
            
            if (range.length > 0) {
                
                self.weatherInfo.AQIInfo = nil;
              //  [self downloadIsFail:nil URL:str_URL];
            }
            else
            {
                [self dealDownloadDataOfAQI:resultDic];
            }

        }
        
        //三次下载完成
    if (self.con.flag_requestTime == 3)
    {
        NSLog(@"=====test success");
        if ([self.delegateOfDealData respondsToSelector:@selector(DownLoadDataHavedDealed:)]) {

            [self.delegateOfDealData DownLoadDataHavedDealed:self.weatherInfo];
        }
    }
    
    }
    
}


//处理下载好的未来5天的天气
-(void)dealDownloadFutureWeather:(NSDictionary*) result
{
    
    NSError *error = nil;
    
    TWFXStruct_FutureWeatherInfo* tempFutureWeather = [[TWFXStruct_FutureWeatherInfo alloc] init];
    
    [TWFXStruct_FutureWeatherInfo FutureWeatherWithDictionary:result FutureWeatherInfo:tempFutureWeather Error:error];
    
    if (error == nil) {
        
        self.weatherInfo.futureWeatherInfo = tempFutureWeather;
    }
    
    [tempFutureWeather release];
    
   // NSLog(@"未来天气处理完成");
}


//处理下载好得aqi的信息
-(void)dealDownloadDataOfAQI:(NSArray*) result
{
    
    NSError *error = nil;
    
    TWFXStruct_AQIInfo *tempAQIInfo = [[TWFXStruct_AQIInfo alloc] init];
    
    
    [TWFXStruct_AQIInfo AQIInfoWithDictionary:result[result.count - 1] AQIInfo:tempAQIInfo Error:error];
    
    //下载的数据正确解析出来
    if (error == nil)
    {
        self.weatherInfo.AQIInfo = tempAQIInfo;
    }
    
    [tempAQIInfo release];

}


//处理下载好得实时天气的信息
-(void)dealDownRealTimeWeather:(NSDictionary*) result
{
    NSError *error = nil;
    
    TWFXStruct_RealTimeWeatherInfo *tempRealTimeInfo = [[TWFXStruct_RealTimeWeatherInfo alloc] init];
    
    [TWFXStruct_RealTimeWeatherInfo RealTimeInfoWithDictionary:result RealTimeData:tempRealTimeInfo Error:error];
    
    //下载的数据正确解析出来
    if (error == nil)
    {
        self.weatherInfo.realTimeWeatherInfo = tempRealTimeInfo;
      //  NSLog(@"haha %@ %@ %@ %@ \n",tempRealTimeInfo.temp, tempRealTimeInfo.WD, tempRealTimeInfo.WS, tempRealTimeInfo.time);
        
    }
    else
    {
        NSLog(@"解析实时天气出错");
    }
    
    [tempRealTimeInfo release];

}



-(void)downloadIsFail:(NSError *)error URL:(NSString *)url
{
    NSLog(@"下载失败 %@",url);
    
    if ([url hasPrefix:@"http://m.weather.com.cn"])
    {
        
        self.weatherInfo.futureWeatherInfo = nil;
    }
    
    else if ([url hasPrefix:@"http://www.weather.com.cn/data/sk/"])
    {
        
        self.weatherInfo.realTimeWeatherInfo = nil;
        NSLog(@"下载 实时天气出错");
        
    }
    else if ([url hasPrefix:@"http://www.pm25.in/api/querys"])
    {
        
        self.weatherInfo.AQIInfo = nil;

    }
    
    if (self.con.flag_requestTime == 3) {
        NSLog(@"=====test fail");
        [self.delegateOfDealData DownLoadDataHavedDealed:nil];
    }
    
}




@end
